package com.wicket.okrapp.biz.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wicket.okrapp.biz.service.DualHighIndicatorRelationshipService;
import com.wicket.okrapp.common.dto.FieldInfo;
import com.wicket.okrapp.common.exception.BizException;
import com.wicket.okrapp.common.tools.StringUtils;
import com.wicket.okrapp.common.util.CommonFunctionHelper;
import com.wicket.okrapp.dal.mapper.mbg.OmsDualHighIndicatorRelationshipMapper;
import com.wicket.okrapp.dal.po.mbg.OmsDualHighIndicatorRelationship;
import org.apache.skywalking.apm.toolkit.trace.Tag;
import org.apache.skywalking.apm.toolkit.trace.Tags;
import org.apache.skywalking.apm.toolkit.trace.Trace;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author  CHS
 * @since 2025-10-02
 *
 *
 * @version 1.0
 */
@Service
public class DualHighIndicatorRelationshipServiceImpl
        extends ServiceImpl<OmsDualHighIndicatorRelationshipMapper, OmsDualHighIndicatorRelationship>
        implements DualHighIndicatorRelationshipService {

    @Autowired
    OmsDualHighIndicatorRelationshipMapper omsDualHighIndicatorRelationshipMapper;

    /**
     * 查双高建设任务绩效关系列表[2536]
     * gen by moon at 10/15/2022, 9:58:55 PM
     */
    @Trace(operationName = "查双高建设任务绩效关系列表")
    @Tags({@Tag(key = "参数",value = "arg[0]"),
            @Tag(key = "返回值",value = "returnedObj")})
    @Override
    @Transactional(rollbackFor=Exception.class)
    public  List<OmsDualHighIndicatorRelationship>  queryDualHighIndicatorRelationshipList(OmsDualHighIndicatorRelationship obj) {

        try {
            QueryWrapper<OmsDualHighIndicatorRelationship> queryWrapper = new QueryWrapper<>();
            obj.setIsValid("FALSE");
            obj.setSpaceId(CommonFunctionHelper.getBaseInfoFromLocal().getSpecSpaceId());//CURRENT_SPACEID

            Map<String, Object> fieldInfoMap = null;
            fieldInfoMap = CommonFunctionHelper.objectToMapForLamBda(obj);
            List<FieldInfo> compareList = CommonFunctionHelper.getRangeField(OmsDualHighIndicatorRelationship.class);
            CommonFunctionHelper.buildQueryWrapperCompare(queryWrapper, compareList, fieldInfoMap);
            List<FieldInfo> likeList = CommonFunctionHelper.getLikeFiled(OmsDualHighIndicatorRelationship.class);
            CommonFunctionHelper.buildQueryWrapperLike(queryWrapper,likeList,fieldInfoMap);
            likeList.addAll(compareList);
            CommonFunctionHelper.buildQueryWrapperEq(queryWrapper, fieldInfoMap,likeList);
            List<FieldInfo> orderList = CommonFunctionHelper.getOrderList(OmsDualHighIndicatorRelationship.class);
            //CommonFunctionHelper.buildQueryWrapperOrder(queryWrapper, orderList);

            return ((List<OmsDualHighIndicatorRelationship>) super.list(queryWrapper));
        } catch (Exception e) {
            e.printStackTrace();
            throw new BizException("-1",e,false);
        }
    }

    /**
     * 查双高建设任务绩效关系详情[2515]
     * gen by moon at 4/24/2023, 12:54:06 AM
     */
    @Trace(operationName = "查双高建设任务绩效关系详情")
    @Tags({@Tag(key = "参数",value = "arg[0]"),
            @Tag(key = "返回值",value = "returnedObj")})
    @Override
    @Transactional(rollbackFor=Exception.class)
    public  OmsDualHighIndicatorRelationship  queryDualHighIndicatorRelationshipDetail(OmsDualHighIndicatorRelationship obj) {

        try {
            obj.setIsValid("FALSE");
            obj.setSpaceId(CommonFunctionHelper.getBaseInfoFromLocal().getSpecSpaceId());//CURRENT_SPACEID
            obj.setAppId(CommonFunctionHelper.getBaseInfoFromLocal().getSpecAppId());//CURRENT_APPID
            QueryWrapper<OmsDualHighIndicatorRelationship> queryWrapper = new QueryWrapper<>();
            Map<String, Object> fieldInfoMap = null;
            fieldInfoMap = CommonFunctionHelper.objectToMapForLamBda(obj);
            CommonFunctionHelper.buildQueryWrapperEq(queryWrapper, fieldInfoMap, new ArrayList<>());
            queryWrapper.orderByDesc("create_time");
            List<OmsDualHighIndicatorRelationship> retList = super.list(queryWrapper);
            if(retList!=null && retList.size()>0){
                OmsDualHighIndicatorRelationship retData = retList.get(0);

                return retData;
            }
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            throw new BizException("-1",e,false);
        }
    }

    /**
     * 新增双高建设任务绩效关系[2346]
     * gen by moon at 10/15/2022, 9:58:53 PM
     */
    @Trace(operationName = "新增双高建设任务绩效关系")
    @Tags({@Tag(key = "参数",value = "arg[0]"),
            @Tag(key = "返回值",value = "returnedObj")})
    @Override
    @Transactional(rollbackFor=Exception.class)
    public  String  addDualHighIndicatorRelationship(OmsDualHighIndicatorRelationship omsDualHighIndicatorRelationship) {
        omsDualHighIndicatorRelationship.setOperateTime(CommonFunctionHelper.getCurrentTime());//SYSTEM_CURRENT_TIME
        omsDualHighIndicatorRelationship.setCreateTime(CommonFunctionHelper.getCurrentTime());//SYSTEM_CURRENT_TIME
        omsDualHighIndicatorRelationship.setIsValid("FALSE");
        omsDualHighIndicatorRelationship.setSpaceId(CommonFunctionHelper.getBaseInfoFromLocal().getSpecSpaceId());//CURRENT_SPACEID
        omsDualHighIndicatorRelationship.setAppId(CommonFunctionHelper.getBaseInfoFromLocal().getSpecAppId());//CURRENT_APPID
        if(super.save(omsDualHighIndicatorRelationship)){
            return omsDualHighIndicatorRelationship.getDualHighId();
        }else {
            return "-1";
        }

    }

    /**
     * 修改双高建设任务绩效关系[2917]
     * gen by moon at 10/15/2022, 9:58:56 PM
     */
    @Trace(operationName = "修改双高建设任务绩效关系")
    @Tags({@Tag(key = "参数",value = "arg[0]"),
            @Tag(key = "返回值",value = "returnedObj")})
    @Override
    @Transactional(rollbackFor=Exception.class)
    public  boolean  updateDualHighIndicatorRelationship(OmsDualHighIndicatorRelationship omsDualHighIndicatorRelationship) {
        omsDualHighIndicatorRelationship.setOperateTime(CommonFunctionHelper.getCurrentTime());//SYSTEM_CURRENT_TIME
        return super.updateById(omsDualHighIndicatorRelationship);
    }

    /**
     * 删除双高建设任务绩效关系[4092]
     * gen by moon at 10/15/2022, 9:58:58 PM
     */
    @Trace(operationName = "删除双高建设任务绩效关系")
    @Tags({@Tag(key = "参数",value = "arg[0]"),
            @Tag(key = "返回值",value = "returnedObj")})
    @Override
    @Transactional(rollbackFor=Exception.class)
    public  boolean  deleteDualHighIndicatorRelationship(String planningId ) {

        return super.removeById(planningId);
    }

    /**
     * 维护双高建设任务绩效关系[2917]
     */
    @Trace(operationName = "维护双高建设任务绩效关系")
    @Tags({@Tag(key = "参数",value = "arg[0]"),
            @Tag(key = "返回值",value = "returnedObj")})
    @Override
    @Transactional(rollbackFor=Exception.class)
    public  boolean  changeDualHighIndicatorRelationship(OmsDualHighIndicatorRelationship omsDualHighIndicatorRelationship) {
        // 1. 根据 omsDualHighIndicatorRelationship 中taskId 是否有值，判断是维护建设任务关系，还是绩效关系
            // 遍历 omsDualHighIndicatorRelationship 的 relations字段
        List<HashMap<String,String>> relations = omsDualHighIndicatorRelationship.getRelations();

        // 提取 relations 中所有的 taskId（即 id 字段），放入 Set 以便快速查找
        Set<String> relationIndicatorIds = relations.stream()
                .map(map -> map.get("id"))  // 假设 id
                .filter(Objects::nonNull)   // 过滤 null
                .collect(Collectors.toSet());

        // 查询 当前 dual_high_id 的所有数据，删除其中不在 relations中的数据
        QueryWrapper<OmsDualHighIndicatorRelationship> queryTaskWrapper = new QueryWrapper<OmsDualHighIndicatorRelationship>();
        queryTaskWrapper.eq("dual_high_id",omsDualHighIndicatorRelationship.getDualHighId());
        queryTaskWrapper.eq("dual_high_name",omsDualHighIndicatorRelationship.getDualHighName());
        queryTaskWrapper.eq("dual_high_no",omsDualHighIndicatorRelationship.getDualHighNo());
        queryTaskWrapper.eq("space_id",CommonFunctionHelper.getBaseInfoFromLocal().getSpecSpaceId());

        List<OmsDualHighIndicatorRelationship> retList = super.list(queryTaskWrapper);
        if (retList != null && !retList.isEmpty()) {
            // 找出需要删除的记录：retList 中 indicatorId 不在 relationIndicatorIds 中的； 包括只有taskID，没有indicatorId的数据也会删除
            List<OmsDualHighIndicatorRelationship> toDelete = retList.stream()
                    .filter(record -> !relationIndicatorIds.contains(record.getIndicatorId()))
                    .collect(Collectors.toList());
            // 执行删除（如果有的话）
            if (!toDelete.isEmpty()) {
                // 获取这些记录的 ID（假设主键是 id）
                List<String> deleteIds = toDelete.stream()
                        .map(OmsDualHighIndicatorRelationship::getRelationshipId)
                        .collect(Collectors.toList());
                super.removeByIds(deleteIds);
                // 或者使用 delete 操作也可以，看你用的是哪种方式
            }
        }

        for(HashMap<String,String> relation:relations){
            String indicatorId = relation.get("id");
            String indicatorName = relation.get("name");
            QueryWrapper<OmsDualHighIndicatorRelationship> queryIndicatorWrapper = new QueryWrapper<OmsDualHighIndicatorRelationship>();
            queryIndicatorWrapper.eq("dual_high_id",omsDualHighIndicatorRelationship.getDualHighId());
            queryIndicatorWrapper.eq("dual_high_name",omsDualHighIndicatorRelationship.getDualHighName());
            queryIndicatorWrapper.eq("dual_high_no",omsDualHighIndicatorRelationship.getDualHighNo());
            queryIndicatorWrapper.eq("indicator_id",indicatorId);
            queryIndicatorWrapper.eq("indicator_name",indicatorName);
            queryIndicatorWrapper.eq("space_id",CommonFunctionHelper.getBaseInfoFromLocal().getSpecSpaceId());
            OmsDualHighIndicatorRelationship result = super.getOne(queryIndicatorWrapper);
            if(result == null){
                OmsDualHighIndicatorRelationship temp = new  OmsDualHighIndicatorRelationship();
                temp.setDualHighId(omsDualHighIndicatorRelationship.getDualHighId());
                temp.setDualHighName(omsDualHighIndicatorRelationship.getDualHighName());
                temp.setDualHighNo(omsDualHighIndicatorRelationship.getDualHighNo());
                temp.setIndicatorId(indicatorId);
                temp.setIndicatorName(indicatorName);
                temp.setCreateTime(CommonFunctionHelper.getCurrentTime());
                temp.setOperateTime(CommonFunctionHelper.getCurrentTime());
                temp.setIsValid("FALSE");
                temp.setSpaceId(CommonFunctionHelper.getBaseInfoFromLocal().getSpecSpaceId());
                temp.setAppId(CommonFunctionHelper.getBaseInfoFromLocal().getSpecAppId());
                super.save(temp);
            }
        }
        return true;
    }

}
